//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.identityaccess.resource;

import com.saasovation.common.media.OvationsMediaType;
import com.saasovation.common.serializer.ObjectSerializer;
import com.saasovation.identityaccess.application.command.ProvisionGroupCommand;
import com.saasovation.identityaccess.application.representation.GroupRepresentation;
import com.saasovation.identityaccess.domain.model.identity.Group;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;

@Path("/tenants/{tenantId}/groups")
public class GroupResource extends AbstractResource {
    public GroupResource() {
        super();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({OvationsMediaType.ID_OVATION_TYPE})
    public Response provisionGroup(ProvisionGroupCommand command) {
        Group group = this.identityApplicationService().provisionGroup(command);
        return Response.ok(group.name()).build();
    }

    @GET
    @Path("{groupName}")
    @Produces({OvationsMediaType.ID_OVATION_TYPE})
    public Response getGroup(@PathParam("tenantId") String aTenantId,
                             @PathParam("groupName") String aGroupName,
                             @Context Request aRequest) {
        Group group = this.identityApplicationService().group(aTenantId, aGroupName);
        if (group == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return this.groupResponse(aRequest, group);
    }

    private Response groupResponse(Request aRequest, Group aGroup) {
        Response response;
        GroupRepresentation representation = new GroupRepresentation(aGroup);
        String representationJson = ObjectSerializer.instance().serialize(representation);
        response = Response.ok(representationJson)
                .cacheControl(this.cacheControlFor(30))
                .build();
        return response;
    }
}
